//
//  ProjectsView.swift
//  GerritHermes
//
//  Created by J.Zhou on 2020/1/13.
//  Copyright © 2020 J.Zhou. All rights reserved.
//

import SwiftUI

struct ProjectsView: View {
    @State var selectedIndex: Int
    @State private var newProject = ""
    @ObservedObject private var model = ProjectsModel.shared

    var body: some View {
        VStack(alignment: .leading) {
            Text("Serving Projects (\(model.projects.count))").font(.headline)

            List {
                ForEach(model.projects.indices, id: \.self) { index in
                    ProjectCell(title: self.model.projects[index], index: index, selectedIndex: self.$selectedIndex)
                }
            }

            HStack {
                Button(action: self.deleteProject) {
                    Text("Delete")
                }
                .disabled(self.model.projects.isEmpty)
            }
            .frame(minWidth: 0, maxWidth: .infinity)

            HStack {
                TextField("Add Project", text: $newProject, onCommit: addProject)
                Button(action: addProject) {
                    Text("Add")
                }
            }
        }
        .padding()
        .frame(width: 350, height: 300)
    }

    private func addProject() {
        if !newProject.isEmpty && !model.projects.contains(newProject) {
            model.projects.append(newProject)
            newProject = ""
        }
    }

    private func deleteProject() {
        if !model.projects.isEmpty && selectedIndex >= 0 && selectedIndex < model.projects.count {
            model.projects.remove(at: selectedIndex)
        }
    }
}

private struct ProjectCell: View {
    var title: String
    var index: Int
    @Binding var selectedIndex: Int

    var body: some View {
        Text(title)
            .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
            .background(Rectangle().fill(index == selectedIndex ? Color.blue : Color.clear))
            .contentShape(Rectangle())
            .onTapGesture {
                self.selectedIndex = self.index
            }
    }
}
